<template>
<form class="tw-liblogin" @keydown.enter="login">
  <div class="tw-liblogin-inputbox xusername">
    <input class="tw-liblogin-input" v-model="username" :placeholder="usernamePlaceholder" type="index" />
  </div>

  <div class="tw-liblogin-inputbox xpassword">
    <input class="tw-liblogin-input" v-model="password" :placeholder="passwordPlaceholder" type="password" />
  </div>

  <div class="tw-liblogin-text xright">
    <div class="tw-liblogin-text-left">
      <span class="tw-liblogin-error">{{errMsg}}</span>
    </div>

    <div class="tw-liblogin-text-right">
      <a class="tw-liblogin-findpwd" :href="findPwdUrl">忘记密码</a>
    </div>
  </div>

  <a class="tw-liblogin-btn" @click="login">登录</a>

  <div class="tw-liblogin-text">
    <div class="tw-liblogin-text-center">
      <span>还没有帐号?</span>
      <a class="tw-liblogin-findpwd" :href="registerUrl">立即注册</a>
    </div>
  </div>
</form>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'

export default {
  name: 'tw-liblogin',

  props,

  mixins: [style],

  data() {
    return {
      username: 'csadmin002',
      password: 'csjyj@002',
      errMsg: ''
    }
  },

  computed: {
    style () {
      return {
        linkColor: this.linkColor
      }
    }
  },

  methods: {
    setStyle () {
      const style = `
        ::root .tw-liblogin-text a {
          color: ${this.linkColor};
        }
      `

      this.addStyle(style)
    },

    login () {
      const vm = this

      if (this.username === '') {
        this.errMsg = '请输入用户名'
        return
      }

      if (this.password === '') {
        this.errMsg = '请输入密码'
        return
      }

      this.errMsg = ''

      this.$ui.login({
        type: 'password',
        username: this.username,
        password: this.password
      }).then(() => {
        window.location.href = vm.loginSuccessUrl || window.$twApp.eco.ecoWebServer
      }).catch((err) => {
        if (err.response && err.response.data) {
          if ([8000, 8001, 8002, 8004, 8007, 8008].includes(err.response.data.errorCode)) {
            vm.errMsg = err.response.data.errorMesage
          } else if (err.response.data.errorCode === 8005) {
            vm.errMsg = '请选择机构及角色'
          } else {
            vm.errMsg = '登录异常，请重试'
          }
        } else {
          vm.errMsg = '网络异常，请重试'
        }
      })
    }
  },

  created () {
    this.login()
  },

  watch: {
    swiperConfig: {
      deep: true,
      handler (val, old) {
        this.init()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
